/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.put.dcs_modeler.fileTypeDataLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Set;
import java.util.logging.Logger;
import org.openide.cookies.SaveCookie;
import org.openide.filesystems.FileAlreadyLockedException;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObjectExistsException;
import org.openide.loaders.MultiDataObject;
import org.openide.nodes.CookieSet;
import org.openide.nodes.Node;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import pl.put.dcs_modeler.visualModelEditor.actions.openSupport.DCSComputingObjectOpenSupport;
import pl.put.dcs_modeler.visualModelEditor.windowComponenets.CFMWindowTopComponent;

public class DCSComputingModelDataObject extends MultiDataObject
{
    private static Logger log =
            Logger.getLogger( DCSComputingModelDataObject.class.getName() );
    
    public DCSComputingModelDataObject( FileObject pf, DCSComputingModelDataLoader loader ) throws DataObjectExistsException, IOException
    {
        super( pf, loader );
        CookieSet cookies = getCookieSet();
        log.info(  "jestesm gjgjgjgjgjjgjg");
        //cookies.add( ( Node.Cookie ) DataEditorSupport.create( this, getPrimaryEntry(), cookies ) );
        cookies.add( ( Node.Cookie ) new DCSComputingObjectOpenSupport( getPrimaryEntry() ) );
    }

    @Override
    protected Node createNodeDelegate()
    {
        return new DCSComputingModelDataNode( this, getLookup() );
    }

    @Override
    public Lookup getLookup()
    {
        return getCookieSet().getLookup();
    }

    public void writeString( String val )
    {
        FileObject fo = getPrimaryFile();
        FileLock lock = new FileLock();

        try
        {
            lock = fo.lock();
        }
        catch ( IOException iOException )
        {
            log.warning( "writeString(): File is locked. Can't write.");
            iOException.printStackTrace();
        }
        
        PrintWriter to = null;
        try
        {
            to = new PrintWriter( fo.getOutputStream( lock ) );
            try
            {
                to.print( val );
            } finally
            {
                to.close();
            }
        }
        catch ( IOException ex )
        {
            log.warning( "writeString(): Error creatig PrintWriter" );
            Exceptions.printStackTrace( ex );
        } finally
        {
            lock.releaseLock();
            to.flush();
            to.close();
        }
        

    }
    
    public String getFileContent()
    {
        FileObject primaryFile = getPrimaryFile();

        String fileContent = new String();
        BufferedReader from = null;
        try
        {
            from = new BufferedReader( new InputStreamReader( primaryFile.getInputStream() ) );
            String line;
            while ((line=from.readLine()) != null)
            {
                fileContent += line;
            }

            /*InputStream inputStream = primaryFile.getInputStream();
            byte[] b = new byte[ 8 ];
            
            while ( inputStream.read( b ) != -1 )
            {
                fileContent += new String( b );
            }*/
        } catch ( IOException ex )
        {
            Exceptions.printStackTrace( ex );
            return null;
        } finally
        {
            try
            {
                from.close();
            }
            catch ( IOException ex )
            {
                Exceptions.printStackTrace( ex );
            }
        };
        return fileContent;
    }

    /**
     * Obiekty sa rowne, jezeli tycza sie tego samego pliku
     * @param obj
     * @return
     */
    @Override
    public boolean equals( Object obj )
    {
        if ( obj instanceof DCSComputingModelDataObject )
        {
            if ( this.getPrimaryFile().getPath().equals( ( ( DCSComputingModelDataObject )obj ).getPrimaryFile().getPath() ) )
            {
                return true;
            }
        }
        return false;
    }

    @Override
    public void setModified( boolean modified )
    {
        
        if ( modified )
        {
            getCookieSet().add( getSaveCookie() );
        }
        else
        {
            getCookieSet().remove( getSaveCookie() );
        }
        super.setModified( modified );
    }

    private SaveCookie getSaveCookie()
    {
        return new SaveCookie()
        {

            @Override
            public void save() throws IOException
            {
                // strasznie malo wydajne, ale nie wiem, jak pobrac okno dla tego DataObject i je zmusic do zapisu
                Set< TopComponent > set = TopComponent.getRegistry().getOpened();
                for ( TopComponent node : set )
                {
                    log.info( node.getName() + "," + node.getDisplayName() );
                    log.info( node.getClass().getName()  );
                    if ( ( node instanceof CFMWindowTopComponent ) && ( ( CFMWindowTopComponent )node ).isBelongToThisTopComponent( DCSComputingModelDataObject.this ) )
                    {
                        ( ( CFMWindowTopComponent )node ).save();
                        setModified( false );
                    }
                }
            }
        };
    }

}
